package com.bysj.sausys.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 文件工具类
 *
 * @author WangZK
 */
public class FileUtil {

    /**
     * 创建文件夹
     *
     * @param path
     */
    public static void createFolder(String path) {
        File folder = new File(path);
        if (!folder.exists()) {
            folder.setWritable(true);
            if (!folder.mkdirs()) {
                throw new RuntimeException("创建文件夹失败");
            }
        }
    }

    /**
     * 判断文件是否存在
     *
     * @param fileName
     * @return
     */
    public static boolean isFileExist(String fileName) {
        return new File(fileName).isFile();
    }

    /**
     * 获取文件的后缀名
     *
     * @param fileName
     * @return
     */
    public static String getFileExt(String fileName) {
        int point = fileName.lastIndexOf('.');
        int length = fileName.length();
        if (point == -1 || point == length - 1) {
            return "";
        } else {
            return fileName.substring(point + 1, length);
        }
    }

    /**
     * 获取新的文件名
     *
     * @param fileName
     * @return
     */
    public static String getNewFileName(String fileName) {
        Format format = new SimpleDateFormat("yyyyMMddHHmmss");
        String newFileName = format.format(new Date()) + fileName;
        return newFileName;
    }

    /**
     * 删除文件
     *
     * @param filename
     * @throws IOException
     */
    public static void deleteFile(String filename) throws IOException {
        File file = new File(filename);
        if (file.isDirectory()) {
            throw new IOException("IOException -> BadInputException: not a file.");
        }
        if (!file.exists()) {
            throw new IOException("IOException -> BadInputException: file is not exist.");
        }
        if (!file.delete()) {
            throw new IOException("Cannot delete file. filename = " + filename);
        }
    }

    /**
     * 将上传的文件复制到服务器上
     *
     * @param uploadFile
     * @param file
     */
    public static void copyFile(MultipartFile uploadFile, File file) {
        try {
            uploadFile.transferTo(file);
        } catch (IOException e) {
            throw new RuntimeException("上传失败");
        }
    }

}
